package com.junjin.testwebview;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    private WebView webView;
    private EditText urlEditText;
    private Button goButton;
    protected String TAG = "MainActivity";

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化视图
        webView = findViewById(R.id.webView);
        urlEditText = findViewById(R.id.urlEditText);
        goButton = findViewById(R.id.goButton);
        Button refreshButton = findViewById(R.id.refreshButton);


        // 配置 WebView
        WebSettings webSetting = webView.getSettings();
        webSetting.setJavaScriptEnabled(true);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setSupportZoom(true);
        webSetting.setDisplayZoomControls(false);
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
        webSetting.setAllowFileAccess(true);
        webSetting.setDefaultTextEncodingName("UTF-8");
        webSetting.setLoadWithOverviewMode(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setDomStorageEnabled(true);
//        webSetting.setCacheMode(WebSettings.LOAD_DEFAULT);
//        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
//        webSetting.setAppCachePath(Application.getContext().getCacheDir().getAbsolutePath());
//        webSetting.setAppCacheEnabled(true);
        //webSetting.setSupportMultipleWindows(true);
        webSetting.setAllowContentAccess(true);
        webSetting.setMinimumFontSize(10);
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
        webSetting.setDefaultFixedFontSize(16);
        webSetting.setDefaultFontSize(16);
        try {//本地HTML里面有跨域的请求 原生webview需要设置之后才能实现跨域请求
            Class<?> clazz = webSetting.getClass();
            Method method = clazz.getMethod(
                    "setAllowUniversalAccessFromFileURLs", boolean.class);
            method.invoke(webSetting, true);
        } catch (IllegalArgumentException | NoSuchMethodException | IllegalAccessException |
                 InvocationTargetException e) {
            e.printStackTrace();
        }
//        if (Build.VERSION.SDK_INT >= 26) {
////            paramHorizontalWebView.setImportantForAutofill(1);
//        } else {
//            webSetting.setSaveFormData(true);
//        }
        // 不缩放
//        setInitialScale(100);
//        webSetting.setTextZoom(100);
//        webSetting.setTextZoom(TextSizeActivity.getTextZoom(mContext));
        // webSetting.setDatabaseEnabled(true);
        webSetting.setGeolocationEnabled(true);
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
//        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
//        webSetting.setBlockNetworkImage(true);
        webSetting.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
//
//        // 设置缓存模式为不使用缓存
//        webSetting.setCacheMode(WebSettings.LOAD_NO_CACHE);
//        // 清除缓存数据
//        webView.clearCache(true);
//
//        CookieManager cookieManager = CookieManager.getInstance();
//        cookieManager.setAcceptCookie(true);
//        CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);

        webView.setWebChromeClient(new WebChromeClient());
        webView.setWebViewClient(new CustomWebViewClient());

//        WebView.setWebContentsDebuggingEnabled(true);
//        addServiceWorkerClient(this);
        // 设置按钮点击事件
        goButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = urlEditText.getText().toString();
                if (!url.startsWith("http://") && !url.startsWith("https://")) {
                    url = "http://" + url;
                }
                webView.loadUrl(url);
            }
        });
        String url = urlEditText.getText().toString();
        if (!url.startsWith("http://") && !url.startsWith("https://")) {
            url = "http://" + url;
        }
//        webView.loadUrl(url);
        refreshButton.setOnClickListener(v -> {
            LoginActivity.actionStart(this);
//            webView.reload();
        });
    }

    private class CustomWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            view.loadUrl(request.getUrl().toString());
            printRequestInfo(request);
            return true;
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            String url = request.getUrl().toString();
            // 在这里添加拦截逻辑，例如拦截特定的资源请求
            if (url.contains("gduamoe.com/upload/ad")) {
                Log.d(TAG, "拦截到资源请求: " + url);
                return new WebResourceResponse(null, null, null);
            }
            printRequestInfo(request);
            return super.shouldInterceptRequest(view, request);
        }

        private void printRequestInfo(WebResourceRequest request) {
            try {
                URL url = new URL(request.getUrl().toString());
                Log.d(TAG, "请求 URL: " + url);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}